package com.ice.base.controller;

import cn.hutool.core.io.IoUtil;
import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;
import com.github.pagehelper.PageHelper;
import com.ice.base.aop.ActiveValidate;
import com.ice.base.aop.ControllerMethodLog;
import com.ice.base.constant.BaseConstant;
import com.ice.base.model.SysLoginModel;
import com.ice.base.model.SysLoginRoleModel;
import com.ice.base.result.ResponseResult;
import com.ice.base.result.AjaxResult;
import com.ice.base.service.SysLoginRoleService;
import com.ice.base.service.SysLoginService;
import com.ice.base.util.BaseUtil;
import com.ice.base.util.JwtUtil;
import com.ice.body.business.model.FaceLogModel;
import com.ice.body.dict.model.SysDept;
import com.ice.body.dict.service.DeptService;
import com.ice.body.hardware.service.FaceLogService;
import com.ice.config.shrio.MyUsernamePasswordToken;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.subject.Subject;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import springfox.documentation.annotations.ApiIgnore;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

@RestController
@ApiIgnore(value = "系统后台-用户管理")
public class SysUserController extends BaseController {


    //---------------------------账户-----------------------start
    @Resource
    private SysLoginService sysLoginService;
    @Resource
    private SysLoginRoleService sysLoginRoleService;
    @Resource
    private DeptService deptService;
    @Resource
    private FaceLogService faceLogService;


    @ApiIgnore(value = "后台刷连记录查询")
    @PostMapping("/faceLog/selectFaceLog")
    public AjaxResult<FaceLogModel> selectFaceLog(FaceLogModel model) {

        AjaxResult r = ResponseResult.success();
        List list;
        try{
            list = faceLogService.searchFaceLogList(model);
            r.setData(list);
        }catch (Exception e){
            e.printStackTrace();
            r = ResponseResult.error();
        }
        return r;
    }


    @ControllerMethodLog(remark = "管理用户登录")
    @ActiveValidate(remark = "校验")
    @ApiOperation(value = "管理用户登录")
    @PostMapping("/base/login")
    public AjaxResult doLogin(@RequestParam("userName") String userName,
                              @RequestParam("password") String password,
                              HttpServletRequest request) {
        HashMap<String, Object> returnMap = getReturnMap();
        try {
            Integer loginFlag = (Integer) request.getAttribute("loginFlag");
        /*    if(loginFlag != 1){
                return AjaxResult.error("系统未激活,请联系管理员");
            }*/
            MyUsernamePasswordToken token = new MyUsernamePasswordToken(userName, password);
            Subject subject = SecurityUtils.getSubject();
            subject.login(token);
            String tokens = JwtUtil.createTokenWithClaim(userName);
            SysLoginModel currLoginModel = BaseUtil.getCurrLoginModel();
            if (currLoginModel != null) {
                currLoginModel.setPassWord(null);//返回时去掉用户信息
                returnMap.put("login", currLoginModel);
                returnMap.put("token", tokens);
                return AjaxResult.success(returnMap);
            }else {
                return AjaxResult.error("用户不存在");
            }
        } catch (IncorrectCredentialsException ice) {
            return AjaxResult.error(BaseConstant.Response_MENU.REQUEST_PASSWORD_FAILED.getDir());
        } catch (UnknownAccountException uae) {
            return AjaxResult.error(BaseConstant.Response_MENU.REQUEST_USER_NAME_FAILED.getDir());
        } catch (LockedAccountException lockedAccountException) {
            return AjaxResult.error("用户被冻结");
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.error("系统错误");
        }
    }

    @ApiIgnore(value = "未登陆")
    @GetMapping("/base/unLogin")
    public HashMap unLogin() {
        HashMap<String, Object> returnMap = new HashMap<>();
        returnMap.put("message", "未登录");
        return returnMap;
    }

    @ApiOperation(value = "用户退出")
    @GetMapping("/base/doLogout.do")
    public HashMap doLogout() {
        HashMap<String, Object> returnMap = getReturnMap();
        Subject subject = SecurityUtils.getSubject();
        if (subject.isAuthenticated()) {
            subject.logout();
            getReturnMapSuccess(returnMap);
        }
        return returnMap;
    }



    @ApiOperation(value = "管理账户-新增")
    @PostMapping("/api_p/SysLogin/insert")
    public AjaxResult insert_SysLogin(HttpServletRequest request, SysLoginModel model) {
        Long deptId = model.getDeptId();
        String rodeId = model.getRoleId();
        if(StringUtils.isEmpty(rodeId) || null == deptId ){
            return AjaxResult.error("部门或角色必选");
        }
        SysDept sysDept = deptService.selectDeptById(deptId);
        if(null == sysDept){
            return AjaxResult.error("部门不存在或已失效");
        }

        try{
            SysLoginModel sysLoginModel = sysLoginService.selectModelByUserName(model.getUserName());
            if(null != sysLoginModel ){
                return AjaxResult.error("用户名重复");
            }
            model.setDelFlag(0);


            if(sysLoginService.insertSysLogin(model) == 1){
                return AjaxResult.success(model);
            }else{
                return AjaxResult.error("创建用户失败");
            }

        }catch (Exception e){
            e.printStackTrace();
            return AjaxResult.error("创建用户失败");
        }
    }

    @ApiOperation(value = "账户-删除")
    @PostMapping("/api_p/SysLogin/deleteById")
    public HashMap deleteById_SysLogin(@RequestParam("id") String id) {
        return delete(sysLoginService, id);
    }

    @ApiOperation(value = "账户-更新")
    @PostMapping("/api_p/SysLogin/updateById")
    public HashMap update_SysLogin(SysLoginModel model) {

        HashMap returnMap = getReturnMap();
        if(StringUtils.isNotEmpty(model.getPassWord()) ){
            BaseUtil.encryptionPassword(model);
        }
        //角色id不为空 给用户授权角色
        if (StringUtils.isNotEmpty(model.getRole_id())) {
            sysLoginRoleService.deleteByLoginId(model.getId());
            SysLoginRoleModel sysLoginRoleModel = new SysLoginRoleModel();
            sysLoginRoleModel.init(sysLoginRoleModel);
            sysLoginRoleModel.setLogin_id(model.getId());
            sysLoginRoleModel.setRole_id(model.getRole_id());
            sysLoginRoleService.insert(sysLoginRoleModel);
        }
        try{
            sysLoginService.update(model);
        }catch (Exception e){
            e.printStackTrace();
            returnMap = getReturnMap(BaseConstant.Response_MENU.REQUEST_DO_FAILED);
        }
        return returnMap;
    }


    @ApiOperation(value = "账户-查询一个")
    @PostMapping("/api_p/SysLogin/selectById")
    public HashMap selectById_SysLogin(@RequestParam("id") Integer id, @RequestParam(name = "selectDetails", required = false) boolean selectDetails) {
        if (selectDetails) {
            HashMap<String, Object> resultMap = getReturnMap(BaseConstant.Response_MENU.REQUEST_SELECT_FAILED);
            //查询一个角色
            SysLoginModel sysRoleModel = sysLoginService.selectDetailsById(id);
            if (sysRoleModel != null) {
                getReturnMapSelect(resultMap, sysRoleModel);
            }
            return resultMap;
        } else {
            return selectById(sysLoginService, id.toString());
        }
    }

/*
    @ApiIgnore(value = "账户-查询多个")
    @PostMapping("/api_p/SysLogin/selectList")
    public HashMap selectList_SysLogin(HttpServletRequest request) {
        return selectListByCondition(request, sysLoginService, new SysLoginModel());
    }*/

    @ApiOperation(value = "账户-查询分页")
    @PostMapping("/api_p/SysLogin/selectListByPageHelper")
    public AjaxResult selectListByPageHelper_SysLogin(HttpServletRequest request,
                                                   @RequestParam(name = "pageSize") Integer pageSize,
                                                   @RequestParam(name = "pageNum") Integer pageNum) {
        SysLoginModel sysLoginModel = new SysLoginModel();
        AjaxResult r = ResponseResult.success();
        ArrayList list;
        try{
            PageHelper.startPage(pageNum, pageSize);
            list = sysLoginService.selectListByModel(sysLoginModel);
            getReturnResultByPage(r,list);
        }catch (Exception e){
            e.printStackTrace();
        }
        return r;
    }

    //http://localhost:8088/api_p/SysLogin/exportUser?pageSize=10&pageNum=1
    @ApiOperation(value = "账户-管理人员数据导出")
    @GetMapping("/api_p/SysLogin/exportUser")
    public void selectListByPageHelper_SysLogin(HttpServletResponse response,
                                                   @RequestParam(name = "pageSize") Integer pageSize,
                                                   @RequestParam(name = "pageNum") Integer pageNum,
                                                   SysLoginModel model) {
        try {
            PageHelper.startPage(pageNum, pageSize);
            List<SysLoginModel> list = sysLoginService.selectListByModel(model);

            // 通过工具类创建writer
            ExcelWriter writer = ExcelUtil.getWriter();
            //自定义标题别名
            writer.addHeaderAlias("userName", "账号");
            writer.addHeaderAlias("nick_name", "名称");
            writer.addHeaderAlias("password", "加密密码");
            writer.addHeaderAlias("phone", "联系电话");
            writer.addHeaderAlias("userType", "用户类别,1管理,2镇街");
            // 合并单元格后的标题行，使用默认标题样式
            writer.merge(16, "管理用户数据");
            // 一次性写出内容，使用默认样式，强制输出标题
            writer.write(list, true);
            response.setContentType("application/vnd.ms-excel;charset=utf-8");
            //test.xls是弹出下载对话框的文件名，不能为中文，中文请自行编码
            String fileName = new String("管理用户数据.xls".getBytes(), "ISO8859-1");
            response.setHeader("Content-Disposition", "attachment;filename=" + fileName);
            ServletOutputStream out = response.getOutputStream();
            writer.flush(out, true);
            // 关闭writer，释放内存
            writer.close();
            //此处记得关闭输出Servlet流
            IoUtil.close(out);

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //---------------------------账户-----------------------end


}
